#include <fstream>  
#include <string>  
#include <sstream>
#include <iostream>
#include <fcntl.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include "UsbIO.h"
using namespace std;

UsbIO::UsbIO(std::string usbPath)
{
    this->usbPath = usbPath;
}

bool UsbIO::ReadPhysicalSector(long long  sector_start, unsigned long byte_counts,
     unsigned char* output_buffer, unsigned long buffer_size)
{
   unsigned long n_bytes;
   unsigned char buffer[513];
   int dev_flag = open(UsbIO::usbPath.c_str(),O_RDONLY);
   if(dev_flag == -1)
   {
     perror("failed to open u disk");
     close(dev_flag);
     return -1;
   }
   else{
     lseek(dev_flag,BYTES_PER_SECTOR*sector_start,SEEK_CUR);
     read(dev_flag,buffer,512); //see in unistd.h(documents),
     memmove((void *)&output_buffer[0], (void *)&buffer[byte_counts], buffer_size);
    //  for(int i=0;i<512;i++){
    //   cout<<output_buffer[i]<<"  ";
    //  }
     close(dev_flag);
     return 0;
  }
}
bool UsbIO::WritePhysicalSector(long long sector_start, unsigned long byte_counts,
unsigned char* input_buffer, unsigned long offset)
{
     int dev_flag = open(UsbIO::usbPath.c_str(),O_RDWR);
     if(dev_flag == -1){
        perror("failed to open u disk");
        return -1;
     }
    unsigned char data[BYTES_PER_SECTOR] = {0};
    memmove(reinterpret_cast<unsigned char*>(data) + offset,
           reinterpret_cast<unsigned char*>(input_buffer),
           byte_counts);
    lseek(dev_flag,BYTES_PER_SECTOR*sector_start,SEEK_CUR);
    write(dev_flag,data,512);
    close(dev_flag);
    return 0;
}
string UsbIO::ConvertHex(unsigned char *md,int nLen)
{
	string strSha1="";
    char hex_chars[]="0123456789ABCDEF";
	unsigned int c = 0;
 
	int nByte = sizeof(unsigned char);
 
	for (int i = 0; i < nLen; i++)
	{
		unsigned int x = 0;
		x = md[i];
		x = md[i] >> 4; 
		c = (md[i] >> 4) & 0x0f;
		strSha1 += hex_chars[c];
		strSha1 += hex_chars[md[i] & 0x0f];
	}
	return strSha1;
}